package org.tp8.sampleapp.jaxb.paging.adapter;

import javax.xml.bind.annotation.adapters.XmlAdapter;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.tp8.sampleapp.jaxb.paging.dto.JaxbPageable;

/**
 * The Class PageableAdapter.
 */
public class PageableAdapter extends XmlAdapter<JaxbPageable, Pageable> {

	/* (non-Javadoc)
	 * @see javax.xml.bind.annotation.adapters.XmlAdapter#marshal(java.lang.Object)
	 */
	@Override
	public JaxbPageable marshal(Pageable pageable) throws Exception {
		JaxbPageable pojo = new JaxbPageable();
		pojo.setOffset(pageable.getOffset());
		pojo.setPageNumber(pageable.getPageNumber());
		pojo.setPageSize(pageable.getPageSize());
		pojo.setSort(SortAdapter.getInstance().marshal(pageable.getSort()));
		return pojo;
	}

	/* (non-Javadoc)
	 * @see javax.xml.bind.annotation.adapters.XmlAdapter#unmarshal(java.lang.Object)
	 */
	@Override
	public Pageable unmarshal(JaxbPageable pojo) throws Exception {
		Sort sort = SortAdapter.getInstance().unmarshal(pojo.getSort());
		PageRequest result;
		if (sort != null) {
			result = new PageRequest(pojo.getPageNumber(), pojo.getPageSize(),
					sort);
		} else {
			result = new PageRequest(pojo.getPageNumber(), pojo.getPageSize());
		}
		return result;
	}

}